'use client';

import { useState, useEffect } from 'react';
import { Breakpoint, DeviceType, Orientation, ResponsiveContext } from '@/types/responsive';

const getBreakpoint = (width: number): Breakpoint => {
  if (width < 640) return Breakpoint.SM;
  if (width < 768) return Breakpoint.MD;
  if (width < 1024) return Breakpoint.LG;
  if (width < 1280) return Breakpoint.XL;
  return Breakpoint.XXL;
};

const getDeviceType = (width: number): DeviceType => {
  if (width < 640) return DeviceType.MOBILE;
  if (width < 1024) return DeviceType.TABLET;
  return DeviceType.DESKTOP;
};

const getOrientation = (): Orientation => {
  if (typeof window !== 'undefined') {
    return window.innerWidth > window.innerHeight 
      ? Orientation.LANDSCAPE 
      : Orientation.PORTRAIT;
  }
  return Orientation.PORTRAIT; // 默认值
};

export default function useBreakpoint(): ResponsiveContext {
  const [breakpoint, setBreakpoint] = useState<Breakpoint>(Breakpoint.LG); // 默认值
  const [deviceType, setDeviceType] = useState<DeviceType>(DeviceType.DESKTOP); // 默认值
  const [orientation, setOrientation] = useState<Orientation>(Orientation.PORTRAIT); // 默认值

  useEffect(() => {
    // 确保在浏览器环境中运行
    if (typeof window === 'undefined') return;

    // 初始化
    const updateValues = () => {
      const width = window.innerWidth;
      const currentBreakpoint = getBreakpoint(width);
      const currentDeviceType = getDeviceType(width);
      const currentOrientation = getOrientation();
      
      setBreakpoint(currentBreakpoint);
      setDeviceType(currentDeviceType);
      setOrientation(currentOrientation);
    };

    // 首次运行
    updateValues();

    // 监听窗口大小变化
    window.addEventListener('resize', updateValues);

    // 监听方向变化 (针对移动设备)
    window.addEventListener('orientationchange', updateValues);

    // 清理函数
    return () => {
      window.removeEventListener('resize', updateValues);
      window.removeEventListener('orientationchange', updateValues);
    };
  }, []);

  // 计算额外的便捷属性
  const isMobile = deviceType === DeviceType.MOBILE;
  const isTablet = deviceType === DeviceType.TABLET;
  const isDesktop = deviceType === DeviceType.DESKTOP;
  const isPortrait = orientation === Orientation.PORTRAIT;
  const isLandscape = orientation === Orientation.LANDSCAPE;

  // 返回响应式上下文对象
  return {
    breakpoint,
    deviceType,
    orientation,
    isMobile,
    isTablet,
    isDesktop,
    isPortrait,
    isLandscape,
  };
} 